package com.sjgtw.cloud.web.commandoUnits.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.commandoUnits.domain.CommandoUnits;
import com.sjgtw.cloud.web.commandoUnits.domain.vo.CommandoUnitsImportVo;
import com.sjgtw.cloud.web.commandoUnits.mapper.CommandoUnitsMapper;
import com.sjgtw.cloud.web.commandoUnits.service.ICommandoUnitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 抢险突击队Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-09
 */
@Service
public class CommandoUnitsServiceImpl implements ICommandoUnitsService
{
    @Autowired
    private CommandoUnitsMapper commandoUnitsMapper;

    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询抢险突击队
     * 
     * @param id 抢险突击队主键
     * @return 抢险突击队
     */
    @Override
    public CommandoUnits selectCommandoUnitsById(Long id)
    {
        return commandoUnitsMapper.selectCommandoUnitsById(id);
    }

    /**
     * 查询抢险突击队列表
     * 
     * @param commandoUnits 抢险突击队
     * @return 抢险突击队
     */
    @Override
    public List<Map<String,Object>> selectCommandoUnitsList(CommandoUnits commandoUnits)
    {
        return commandoUnitsMapper.selectCommandoUnitsList(commandoUnits);
    }

    @Override
    public List<CommandoUnitsImportVo> selectExportCommandoUnitsList(CommandoUnits commandoUnits) {
        return commandoUnitsMapper.selectExportCommandoUnitsList(commandoUnits);
    }

    /**
     * 新增抢险突击队
     * 
     * @param commandoUnits 抢险突击队
     * @return 结果
     */
    @Override
    public int insertCommandoUnits(CommandoUnits commandoUnits)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        String username = user.getUsername();

        commandoUnits.setCreateBy(username);
        commandoUnits.setCreateTime(new Date());
        return commandoUnitsMapper.insertCommandoUnits(commandoUnits);
    }

    /**
     * 修改抢险突击队
     * 
     * @param commandoUnits 抢险突击队
     * @return 结果
     */
    @Override
    public int updateCommandoUnits(CommandoUnits commandoUnits)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        String username = user.getUsername();

        commandoUnits.setUpdateBy(username);
        commandoUnits.setUpdateTime(new Date());
        return commandoUnitsMapper.updateCommandoUnits(commandoUnits);
    }

    /**
     * 批量删除抢险突击队
     * 
     * @param ids 需要删除的抢险突击队主键
     * @return 结果
     */
    @Override
    public int deleteCommandoUnitsByIds(Long[] ids)
    {
        return commandoUnitsMapper.deleteCommandoUnitsByIds(ids);
    }

    /**
     * 删除抢险突击队信息
     * 
     * @param id 抢险突击队主键
     * @return 结果
     */
    @Override
    public int deleteCommandoUnitsById(Long id)
    {
        return commandoUnitsMapper.deleteCommandoUnitsById(id);
    }

    @Override
    public List<String> check(List<CommandoUnitsImportVo> entities) {

        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> userNames = extractAndDeduplicateUserNames(entities);

        AjaxResult userResult = systemServerService.getUserByNames(StringUtils.join(userNames, ","));
        Map<String, Long> userMap = new HashMap<>();
        if (userResult != null) {
            Object object = userResult.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        userMap.put(json.getString("userName"), json.getLong("userId"));
                    }
                }
            }
        }


        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (CommandoUnitsImportVo entity : entities) {
            if (StringUtils.isEmpty(entity.getDeptName())) {
                errors.add("序号为" + entity.getNum() + "行数据单位不能为空");
            } else if (deptMap.containsKey(entity.getDeptName())) {
                entity.setDeptId(deptMap.get(entity.getDeptName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据单位不存在");
            }


            if (StringUtils.isEmpty(entity.getLeaderName())) {
                errors.add("序号为" + entity.getNum() + "行数据队长姓名不能为空");
            } else if (userMap.containsKey(entity.getLeaderName())) {
                entity.setLeaderId(userMap.get(entity.getLeaderName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据队长姓名不存在");
            }


            if (StringUtils.isEmpty(entity.getAssistantName())) {
                errors.add("序号为" + entity.getNum() + "行数据副队长姓名不能为空");
            } else {

                String[] split = entity.getAssistantName().split(",");
                if(split.length>0){
                    String assistantId = "";
                    for (int i = 0; i < split.length; i++) {
                        if (userMap.containsKey(split[i])){
                            assistantId  += userMap.get(entity.getLeaderName())+",";
                        }else{
                            errors.add("序号为" + entity.getNum() + "副队长姓名:"+split[i]+"不存在");
                        }
                    }
                    entity.setAssistantId(assistantId.substring(0,assistantId.length()-1));
                }

            }

            if (user != null) {
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<CommandoUnitsImportVo> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<CommandoUnitsImportVo> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        commandoUnitsMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                commandoUnitsMapper.batchSave(entities);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<CommandoUnitsImportVo> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (CommandoUnitsImportVo entity : entities) {
            uniqueNamesSet.add(entity.getDeptName());
        }

        return new ArrayList<>(uniqueNamesSet);
    }

    private static List<String> extractAndDeduplicateUserNames(List<CommandoUnitsImportVo> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (CommandoUnitsImportVo entity : entities) {
            uniqueNamesSet.add(entity.getLeaderName());
            String[] split = entity.getAssistantName().split(",");
            if(split.length>0){
                for (int i = 0; i < split.length; i++) {
                    uniqueNamesSet.add(split[i]);
                }
            }

        }

        return new ArrayList<>(uniqueNamesSet);
    }

}
